<template>
    <view class="overall">
        <view class="content">
            <view class="inner">
                <view>
                    <view>在线建卡</view>
                    <view>无院内就诊ID号，初次就诊选择在线建卡</view>
                </view>
                <view class="form-container">
                    <input type="number" v-model="value1" placeholder="请输入身份证号" class="form-input" @input="handleIdCardInput" />
                    <input type="text" v-model="value2" placeholder="请输入身份证姓名" class="form-input" />
                    <input type="number" v-model="value3" placeholder="请输入手机号" class="form-input" @input="handlePhoneInput" />
                    <input type="text" v-model="value4" placeholder="请输入和您的关系" class="form-input" />
                    <input type="text" v-model="value5" placeholder="请输入联系地址" class="form-input" />
                    <view class="input-group">
                        <input type="text" v-model="value6" placeholder="请输入就诊卡号" class="form-input" @input="handleCardInput" />
                        <view v-if="cardError" class="error-tip">{{ cardError }}</view>
                    </view>
                    
                    <!-- 日期选择组件 -->
                    <view class="input-group date-group">
                        <view class="date-picker-container">
                            <view class="date-picker-label">出生日期：</view>
                            <picker mode="date" :value="value8" :end="today" @change="onDateChange">
                                <view class="date-picker-value">
                                    {{ value8 || '请选择出生日期' }}
                                    <view class="date-picker-arrow"></view>
                                </view>
                            </picker>
                        </view>
                        <view v-if="dateError" class="error-tip date-error-tip">{{ dateError }}</view>
                    </view>
                    
                    <view class="radio-group">
                        <view class="radio-label">性别：</view>
                        <view class="radio-item">
                            <view class="radio-icon" :class="{ 'radio-checked': value7 === '1' }"></view>
                            <view>男</view>
                        </view>
                        <view class="radio-item">
                            <view class="radio-icon" :class="{ 'radio-checked': value7 === '2' }"></view>
                            <view>女</view>
                        </view>
                    </view>
                </view>
                <view>
                    <button @click="create()" class="submit-button" :disabled="formDisabled">立即建卡</button>
                </view>
            </view>
        </view>
    </view>
</template>

<script lang="ts" setup>
    import { ref, computed, onMounted } from 'vue';
    import { cardCreate } from '@/api/index.js';
    
    function handleClickLeft() {
        uni.navigateBack();
    }

    const value1 = ref<string>(''); // 身份证号
    const value2 = ref<string>(''); // 姓名
    const value3 = ref<string>(''); // 手机号
    const value4 = ref<string>(''); // 关系
    const value5 = ref<string>(''); // 地址
    const value6 = ref<string>(''); // 就诊卡号（限制不超过6位）
    const value7 = ref<string>(''); // 性别，根据身份证自动生成
    const value8 = ref<string>(''); // 出生日期
    
    // 错误提示
    const cardError = ref<string>('');
    const dateError = ref<string>('');
    
    // 今天的日期（格式：YYYY-MM-DD）
    const today = ref<string>('');
    
    // 表单禁用状态
    const formDisabled = computed(() => {
        return !!cardError.value || !!dateError.value;
    });

    // 身份证号正则表达式
    const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    // 手机正则表达式
    const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;

    // 获取今天的日期
    const getToday = () => {
        const date = new Date();
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    // 异步获取用户ID
    const getUserId = async () => {
        try {
            const res = await uni.getStorage({ key: 'user' });
            return res.data?.data?.id;
        } catch (error) {
            console.error('获取用户ID失败:', error);
            uni.showToast({
                title: '获取用户信息失败，请重新登录',
                icon: 'none',
                duration: 3000
            });
            return null;
        }
    };

    // 日期选择器变更处理
    const onDateChange = (e: any) => {
        const selectedDate = e.detail.value;
        // 验证日期是否大于今天
        if (selectedDate > today.value) {
            dateError.value = '出生日期不能大于今天';
            value8.value = '';
            uni.showToast({
                title: '出生日期不能大于今天',
                icon: 'none',
                duration: 3000
            });
        } else {
            dateError.value = '';
            value8.value = selectedDate;
        }
    };

    // 处理身份证号输入（限制18位）
    const handleIdCardInput = (e: any) => {
        const inputValue = e.detail.value;
        if (inputValue.length > 18) {
            value1.value = inputValue.slice(0, 18);
        } else {
            value1.value = inputValue;
        }
        
        // 根据身份证号自动识别性别
        if (value1.value.length === 18) {
            // 18位身份证，第17位为性别位
            const genderDigit = parseInt(value1.value.charAt(16));
            value7.value = genderDigit % 2 === 1 ? '1' : '2';
        } else if (value1.value.length === 15) {
            // 15位身份证，第15位为性别位
            const genderDigit = parseInt(value1.value.charAt(14));
            value7.value = genderDigit % 2 === 1 ? '1' : '2';
        } else {
            // 身份证号长度不足，清空性别
            value7.value = '';
        }
    };

    // 处理手机号输入（限制11位）
    const handlePhoneInput = (e: any) => {
        const inputValue = e.detail.value;
        if (inputValue.length > 11) {
            value3.value = inputValue.slice(0, 11);
        }
    };

    // 处理就诊卡号输入（限制不超过6位）
    const handleCardInput = (e: any) => {
        const inputValue = e.detail.value;
        if (inputValue.length > 6) {
            value6.value = inputValue.slice(0, 6);
            cardError.value = '就诊卡号不能超过6位';
        } else {
            cardError.value = '';
        }
    };

    async function create() {
        // 重置错误提示
        cardError.value = '';
        dateError.value = '';
        
        // 表单验证
        if (value1.value === '' || value2.value === '' || value3.value === '' || 
            value4.value === '' || value5.value === '' || value6.value === '' || 
            value7.value === '' || value8.value === '') {
            uni.showToast({
                title: '建卡信息不能为空',
                icon: 'none',
                duration: 3000,
            });
            return;
        }

        // 单独验证身份证号和手机号格式
        let isFormValid = true;
        let errorMessage = '';

        const isIdCardValid = idCardReg.test(value1.value);
        if (!isIdCardValid) {
            isFormValid = false;
            errorMessage = '请输入正确的身份证号';
        }

        const isPhoneValid = phoneReg.test(value3.value);
        if (!isPhoneValid) {
            isFormValid = false;
            errorMessage = errorMessage ? 
                '请输入正确的身份证号和手机号' : 
                '请输入正确的手机号';
        }

        if (!isFormValid) {
            uni.showToast({
                title: errorMessage,
                icon: 'none',
                duration: 3000,
            });
            return;
        }

        // 检查就诊卡号长度（不超过6位且至少1位）
        if (value6.value.length < 1 || value6.value.length > 6) {
            cardError.value = '就诊卡号不能超过6位且至少1位';
            uni.showToast({
                title: '就诊卡号不能超过6位且至少1位',
                icon: 'none',
                duration: 3000,
            });
            return;
        }

        // 检查出生日期
        if (!value8.value) {
            dateError.value = '请选择出生日期';
            uni.showToast({
                title: '请选择出生日期',
                icon: 'none',
                duration: 3000,
            });
            return;
        }

        // 获取用户ID并提交表单
        const userId = await getUserId();
        if (!userId) return;

        try {
            const res = await cardCreate({
                user_id: userId,
                code: value1.value,
                relationship: value4.value,
                nickname: value2.value,
                tel: value3.value,
                address: value5.value,
                card: value6.value,
                sex: value7.value,
                datetime: value8.value
            });

            console.log(res);
            if (res.code === 1) {
                uni.showModal({
                    title: '提示',
                    content: '就诊卡添加成功',
                    showCancel: false,
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                            uni.navigateBack({ delta: 1 });
                        }
                    }
                });
            } else {
                uni.showModal({
                    title: '提示',
                    content: res.msg || '就诊卡添加失败',
                    showCancel: false,
                    success: function (res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                        }
                    }
                });
            }
        } catch (error) {
            console.error('建卡请求失败:', error);
            uni.showToast({
                title: '网络请求失败，请稍后重试',
                icon: 'none',
                duration: 3000
            });
        }
    }

    // 组件挂载时初始化今天的日期
    onMounted(() => {
        today.value = getToday();
    });
</script>

<style scoped>
    .overall {
        width: 100%;
        background-color: #FFFFFF;
        min-height: 100vh;
    }

    .title {
        width: 100%;
        height: 180rpx;
        background-color: #00DACA;
        color: white;
        display: flex;
        align-items: center;
    }

    .name {
        display: flex;
        align-items: center;
        font-weight: bold;
        font-size: 42rpx;
        margin-top: 50rpx;
        margin-left: 3%;
    }

    .name > view {
        margin-left: 20rpx;
    }

    .arrow-left {
        width: 18rpx;
        height: 18rpx;
        border-top: 2rpx solid white;
        border-left: 2rpx solid white;
        transform: rotate(-45deg);
    }

    .content {
        width: 100%;
        min-height: 80vh;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .inner {
        width: 92%;
        min-height: 60vh;
        margin-top: 10%;
    }

    .inner > view {
        color: #999999;
    }

    .inner > view > view:first-child {
        font-size: 38rpx;
        color: black;
        margin-bottom: 20rpx;
    }

    .form-container {
        padding: 80rpx 0;
        min-height: 360rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .input-group {
        position: relative;
    }

    .form-input {
        width: 95%;
        height: 80rpx;
        border: 1rpx solid #EEEEEE;
        border-radius: 8rpx;
        padding: 0 20rpx;
        margin-bottom: 30rpx;
        font-size: 32rpx;
    }

    .error-tip {
        position: absolute;
        right: 20rpx;
        bottom: 5rpx;
        font-size: 24rpx;
        color: #FF5252;
    }

    .date-group {
        margin-bottom: 30rpx;
    }

    .date-error-tip {
        bottom: -25rpx;
    }

    .submit-button {
        width: 100%;
        height: 90rpx;
        background-color: #3ECCB2;
        color: #FFFFFF;
        border: none;
        font-size: 36rpx;
        font-weight: 500;
        opacity: 0.7;
        cursor: not-allowed;
    }
    
    .submit-button:not(:disabled) {
        opacity: 1;
        cursor: pointer;
    }
    
    .radio-group {
        display: flex;
        align-items: center;
        margin-bottom: 30rpx;
        margin-left: 2%;
    }
    
    .radio-label {
        font-size: 32rpx;
        margin-right: 20rpx;
    }
    
    .radio-item {
        display: flex;
        align-items: center;
        margin-right: 40rpx;
        cursor: default;
        opacity: 0.7;
    }
    
    .radio-icon {
        width: 30rpx;
        height: 30rpx;
        border: 2rpx solid #CCCCCC;
        border-radius: 50%;
        margin-right: 10rpx;
    }
    
    .radio-checked {
        border-color: #3ECCB2;
        background-color: #3ECCB2;
        position: relative;
    }
    
    .radio-checked::after {
        content: '';
        position: absolute;
        width: 14rpx;
        height: 14rpx;
        background-color: white;
        border-radius: 50%;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    
    /* 日期选择器样式 */
    .date-picker-container {
        display: flex;
        align-items: center;
        border: 1rpx solid #EEEEEE;
        border-radius: 8rpx;
        padding: 0 20rpx;
        height: 80rpx;
    }
    
    .date-picker-label {
        font-size: 32rpx;
        color: #333;
        margin-right: 20rpx;
    }
    
    .date-picker-value {
        flex: 1;
        font-size: 32rpx;
        color: #999;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    
    .date-picker-value:not(:empty) {
        color: #333;
    }
    
    .date-picker-arrow {
        width: 16rpx;
        height: 16rpx;
        border-top: 2rpx solid #999;
        border-right: 2rpx solid #999;
        transform: rotate(135deg);
    }
</style>
    